require 'fastlane/action'

module Fastlane
  module Actions
    module SharedValues
      # CREATE_PODFILE_CUSTOM_VALUE = :CREATE_PODFILE_CUSTOM_VALUE
    end

    class CreatePodfileAction < Action
      def self.run(params)
        UI.message("The create_podfile Action is working!")

        sources = params[:source]
        version = params[:version]
        sdk_name_string = params[:sdk]
        podfile_path = params[:podfile]
        # // notification service target
        notification_service_target = params[:notification_service_target]

        FastlaneCore::PrintTable.print_values(
          config:params,
          title:'Params'
        )


        File.open(podfile_path,'w') do |file|

          #写入source
          unless (sources.nil? || sources.empty?)
            source_list = sources.split(',')
            if source_list.is_a?(Array) && source_list.count > 0
              source_list.each do |s|
                file.puts "source '#{s}'"
              end
            end
          end
          file.puts "source 'https://cdn.cocoapods.org'"
          file.puts "\n"
          #写入版本
          file.puts "platform :ios, '12.0'"
          file.puts "\n"

          #写入main target
          file.puts "target 'Unity-iPhone' do"
          file.puts "\n"
          file.puts "end"
          file.puts "\n"

          # //写入对应的pod库
          unless (sdk_name_string.nil? || sdk_name_string.empty?)
            sdK_name_array = sdk_name_string.split(',')
            if sdK_name_array.is_a?(Array) && sdK_name_array.count > 0
              file.puts("target 'UnityFramework' do")
              sdK_name_array.each do |sdk_name|
                pod = " pod '#{sdk_name}'"
                pod << ", '#{version}'" if version
                file.puts(pod)
              end
              file.puts("end")
            end
          end

          unless (notification_service_target.nil? || notification_service_target.empty?)
            file.puts("target '#{notification_service_target}' do")
            file.puts("pod 'EPSDK_PushReport'")
            file.puts("pod 'EPSDK_PushService'")
            file.puts("end")
          end

          #写入hook
          file.puts "\n"
          file.puts "# install hook"
          file.write(install_post_code)

        end


      end

      def self.install_post_code
        code =
          'post_install do |installer|
  change_xccofig(installer,\'Pods-Unity-iPhone\',"OTHER_LDFLAGS","$(inherited) -ObjC\n")
end

def find_line_with_start(str, start)
  str.each_line do |line|
      if line.start_with?(start)
            return line
      end
  end
  return nil
  end

def change_xccofig(installer,target_name,config_name,config_value)
  installer.pods_project.targets.each do |target|
    if target.name != target_name
      next
    end
    target.build_configurations.each do |config|
      xcconfig_path = config.base_configuration_reference.real_path
      xcconfig = File.read(xcconfig_path)
      old_line = find_line_with_start(xcconfig, config_name)

      if old_line == nil
        next
      end
      new_line = "#{config_name} = #{config_value}"
      new_xcconfig = xcconfig.sub(old_line, new_line)
      File.open(xcconfig_path, "w") { |file| file << new_xcconfig }
    end
  end
end'
      end

      #####################################################
      # @!group Documentation
      #####################################################

      def self.description
        'A short description with <= 80 characters of what this action does'
      end

      def self.details
        # Optional:
        # this is your chance to provide a more detailed description of this action
        'You can use this action to do cool things...'
      end

      def self.available_options
        # Define all options your action supports.

        # Below a few examples
        [
          FastlaneCore::ConfigItem.new(key: :source,
                                       env_name: "EP_SDK_SOURCE",
                                       description: "The source of podfile",
                                       optional: true,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :version,
                                       env_name: "EP_SDK_VERSION",
                                       description: "The version of sdk",
                                       optional: true,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :sdk,
                                       env_name: "EP_SDK_LIST",
                                       description: "The sdk list of podfile,array use ,",
                                       optional: true,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :notification_service_target,
                                       env_names: ['FASTLANE_NOTIFICATION_SERVICE_TARGET_NAME','ELEX_NOTIFICATION_SERVICE_TARGET_NAME'],
                                       description: "The target name of notofication target name",
                                       optional: true,
                                       type: String),

          FastlaneCore::ConfigItem.new(key: :podfile,
                                       env_names: ['ELEX_COCOAPODS_PODFILE','FL_COCOAPODS_PODFILE'],
                                       description: "The path of podfile",
                                       default_value: "./Podfile",
                                       optional: true,
                                       type: String)
        ]
      end

      def self.output
        # Define the shared values you are going to provide
        # Example
        [
          # ['ELEX_PODFILE_OUTPUT_PATH', 'The path of Podfile']
        ]
      end

      def self.return_value
        # If your method provides a return value, you can describe here what it does
      end

      def self.authors
        # So no one will ever forget your contribution to fastlane :) You are awesome btw!
        ['Loong Yan']
      end

      def self.is_supported?(platform)
        # you can do things like
        #
        #  true
        #
        #  platform == :ios
        #
        #  [:ios, :mac].include?(platform)
        #

        platform == :ios
      end
    end
  end
end

